﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MxWeiXinPF.Common;
using MxWeiXinPF.WeiXinComm;
using MxWeiXinPF.Web.api.payment.wxpay;
using System.Xml;
using MxWeiXinPF.Web.bussiness;
using MxWeiXinPF.Web.bussiness.coupon;

namespace MxWeiXinPF.Web
{
    public partial class WfTimedExecService : Page
    {
        private WeiXinCRMComm cpp = new WeiXinCRMComm();
        public static string PostUrl = ConfigurationManager.AppSettings["WebReference.Service.PostUrl"];
        public static string Pwd = ConfigurationManager.AppSettings["WebReference.Service.Pwd"];
        private WeiXinSendMessageComm sm = new WeiXinSendMessageComm();
        public static string UserName = ConfigurationManager.AppSettings["WebReference.Service.UserName"];

        private void AutoComplete(DataSet ds)
        {
            MxWeiXinPF.BLL.orders orders = new MxWeiXinPF.BLL.orders();
            DataSet set = new DataSet();
            if ((ds != null) && (ds.Tables[0].Rows.Count > 0))
            {
                try
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        if (!string.IsNullOrEmpty(ds.Tables[0].Rows[i]["id"].ToString()))
                        {
                            set = orders.InsertIntoDtUserRate(int.Parse(ds.Tables[i].Rows[0]["id"].ToString()));
                            if ((set != null) && (set.Tables.Count > 0))
                            {
                                if (ds.Tables[0].Rows[i]["payment_id"].ToString().Trim().Equals("1"))
                                {
                                    if (orders.UpdateField(ds.Tables[0].Rows[i]["id"].ToString().Trim(), " express_status=2,payment_status=2 , status=3,complete_time=getdate() "))
                                    {
                                        SendWxMessage(int.Parse(ds.Tables[0].Rows[i]["id"].ToString().Trim()));
                                    }
                                }
                                else if (orders.UpdateField(ds.Tables[0].Rows[i]["id"].ToString().Trim(), " express_status=2,payment_status=2 , status=3,complete_time=getdate() "))
                                {
                                    //orders.WXSendMessage(int.Parse(ds.Tables[0].Rows[i]["id"].ToString().Trim()));
                                    SendWxMessage(int.Parse(ds.Tables[0].Rows[i]["id"].ToString().Trim()));
                                }
                            }
                        }
                    }
                }
                catch (Exception)
                {
                }
            }
        }

        private DataSet AutoGetComplete()
        {
            MxWeiXinPF.BLL.orders orders = new MxWeiXinPF.BLL.orders();
            DataSet set = new DataSet();
            try
            {
                return orders.GetSetComplete();
            }
            catch (Exception)
            {
                return null;
            }
        }

        private DataSet AutoGetTemplate()
        {
            MxWeiXinPF.BLL.sendmessage sendmessage = new MxWeiXinPF.BLL.sendmessage();
            DataSet set = new DataSet();
            try
            {
                return sendmessage.GetTemplateMessage();
            }
            catch (Exception)
            {
                return null;
            }
        }

        private DataSet AutoGetTSMS()
        {
            MxWeiXinPF.BLL.sendmessage sendmessage = new MxWeiXinPF.BLL.sendmessage();
            DataSet set = new DataSet();
            try
            {
                return sendmessage.GetSmsMessage();
            }
            catch (Exception)
            {
                return null;
            }
        }

        private DataSet GetWxPay()
        {
            MxWeiXinPF.BLL.dt_transfer orders = new MxWeiXinPF.BLL.dt_transfer();
            DataSet set = new DataSet();
            try
            {
                return orders.GetList("  status = 0 and wid = 39 and shopid <> 39");
            }
            catch (Exception)
            {
                return null;
            }
        }

        private void Transfer()
        {
            object idx = CacheHelper.Get("transfer");
            if (idx == null)
            {
                CacheHelper.Insert("transfer", true);
            }
            else
            {
                bool state = (bool)idx;
                if (state)
                {
                    return;
                }
            }
            CacheHelper.Insert("transfer", true);
            DataSet ds = new DataSet();
            BLL.manager bman = new BLL.manager();
            qypay pays = new qypay();
            MxWeiXinPF.BLL.dt_transfer btran = new MxWeiXinPF.BLL.dt_transfer();
            BLL.orders border = new BLL.orders();
            ds = this.GetWxPay();
            if ((ds != null) && (ds.Tables[0].Rows.Count > 0))
            {
                for (int k = 0; k < ds.Tables[0].Rows.Count; k++)
                {
                    try
                    {
                        int shopid = Convert.ToInt32(ds.Tables[0].Rows[k]["shopid"].ToString());
                        if (shopid ==39)
                        {
                            continue;
                        }
                        int tid = int.Parse(ds.Tables[0].Rows[k]["id"].ToString());
                        Model.dt_transfer mtran = btran.GetModel(tid);
                        mtran.pay_time = DateTime.Now;
                        mtran.status = 1;
                        if(!btran.Update(mtran))
                        {
                            LogHelper.WriteLog(typeof(WfTimedExecService), string.Concat("添加企业向店铺转账失败,由于更新订单状态失败:", tid.ToString()));
                            continue;
                        }
                        int orderid = Convert.ToInt32(ds.Tables[0].Rows[k]["orderid"].ToString());
                        Model.manager mman = bman.GetModel(shopid);
                        Model.orders moder = border.GetModel(orderid);
                        if (moder == null || moder.transfer_fee < 1m)
                        {
                            LogHelper.WriteLog(typeof(WfTimedExecService), string.Concat("添加企业向店铺转账失败,由于订单金额少于1元,订单号码为:", tid.ToString()));
                            continue;
                        }
                        string xml = pays.Transfer("1", moder.transfer_fee, mman.shopclerkid, mman.real_name);
                        SortedDictionary<string, object> mvals = FromXml(xml);
                        if (mvals == null)
                        {
                            mtran.status = 0;
                            btran.Update(mtran);
                            //添加记录失败,记录日志
                            LogHelper.WriteLog(typeof(WfTimedExecService), string.Concat("添加企业向店铺转账记录失败，返回失败", mvals["return_msg"], mvals["result_code"], mvals["err_code"]));
                            continue;
                        }
                        if (mvals["return_code"].ToString().ToUpper() == "SUCCESS" && mvals["return_code"].ToString().ToUpper() == "SUCCESS" && mvals["return_msg"].ToString() == "") //返回失败
                        {
                            LogHelper.WriteLog(typeof(WfTimedExecService), string.Concat("添加企业向店铺转账成功,订单号码为:", tid.ToString()));
                        }
                        else
                        {
                            mtran.status = 0;
                            btran.Update(mtran);
                            //添加记录失败,记录日志
                            LogHelper.WriteLog(typeof(WfTimedExecService), string.Concat("添加企业向店铺转账记录失败，返回失败", mvals["return_msg"], mvals["result_code"], mvals["err_code"]));
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.WriteLog(typeof(WfTimedExecService), string.Concat("异常内容", ex.Message));
                    }
                }
            }
            CacheHelper.Insert("transfer", false);
        }
        private void AutoSetSMS(DataSet ds)
        {
            MxWeiXinPF.BLL.sendmessage sendmessage = new MxWeiXinPF.BLL.sendmessage();
            if ((ds != null) && (ds.Tables[0].Rows.Count > 0))
            {
                try
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        int id = 0;
                        if (!ds.Tables[0].Rows[i]["id"].ToString().Equals(""))
                        {
                            id = int.Parse(ds.Tables[0].Rows[i]["id"].ToString());
                        }
                        this.SendSMSMessage(ds.Tables[0].Rows[i]["mobile"].ToString(), ds.Tables[0].Rows[i]["MessageContent"].ToString());
                        sendmessage.UpdateIsSend("1", DateTime.Now, id);
                    }
                }
                catch (Exception)
                {
                }
            }
        }

        private void AutoSetTemplate(DataSet ds)
        {
            MxWeiXinPF.BLL.sendmessage sendmessage = new MxWeiXinPF.BLL.sendmessage();
            if ((ds != null) && (ds.Tables[0].Rows.Count > 0))
            {
                try
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        int id = 0;
                        if (!ds.Tables[0].Rows[i]["id"].ToString().Equals(""))
                        {
                            id = int.Parse(ds.Tables[0].Rows[i]["id"].ToString());
                        }

                        string openid = ds.Tables[0].Rows[i]["openid"] == null ? "" : ds.Tables[0].Rows[i]["openid"].ToString();
                        string phone = ds.Tables[0].Rows[i]["mobile"] == null ? "" : ds.Tables[0].Rows[i]["mobile"].ToString();
                        bool flag = false;
                        if (!string.IsNullOrEmpty(openid))
                        {
                            string str = "";
                            try
                            {
                                str = this.sm.SendMessageGouYaoTiXin(ds.Tables[0].Rows[i]["openid"].ToString(), 0x27, ds.Tables[0].Rows[i]["truename"].ToString(), ds.Tables[0].Rows[i]["MessageContent"].ToString(), ds.Tables[0].Rows[i]["productname"].ToString(), MyCommFun.getWebSite() + "/wxoauth.aspx?wid=39&p=1");
                                if (str == "请求成功")
                                {
                                    flag = true;
                                }
                            }
                            catch (Exception)
                            {
                                flag = false;
                            }
                        }
                        if (!flag)
                        {
                            admin.sms.BlueSmsMgr mgr = new MxWeiXinPF.Web.admin.sms.BlueSmsMgr(39);
                            if (!string.IsNullOrEmpty(phone))
                            {
                                mgr.SendSMS(phone, ds.Tables[0].Rows[i]["MessageContent"].ToString());
                            }
                        }
                        sendmessage.UpdateIsSend("2", DateTime.Now, id);
                    }
                }
                catch (Exception)
                {
                }
            }
        }

        protected void btnSendMessage_Click(object sender, EventArgs e)
        {
        }

        public string GetHtmlFromUrl(string Phone, string ContentTxt)
        {
            string format = "account={0}&pswd={1}&mobile={2}&msg={3}&needstatus=true&product=&extno=";
            byte[] bytes = new UTF8Encoding().GetBytes(string.Format(format, new object[] { UserName, Pwd, Phone, ContentTxt }));
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(PostUrl);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = bytes.Length;
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(bytes, 0, bytes.Length);
            requestStream.Flush();
            requestStream.Close();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            if (response.StatusCode == HttpStatusCode.OK)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                return "1";
            }
            return "";
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            int hour = Convert.ToInt32(DateTime.Now.Hour.ToString());
            int min = Convert.ToInt32(DateTime.Now.Minute.ToString());
            //if (((hour >= 9) && (hour <= 13)) || ((hour >= 17) && (hour <= 21)))
            //{
                try
                {
                    //DataSet ds = new DataSet();
                    //ds = this.AutoGetComplete();
                    //if ((ds != null) && (ds.Tables[0].Rows.Count > 0))
                    //{
                    //    this.AutoComplete(ds);
                    //}
                    //DataSet set2 = new DataSet();
                    //set2 = this.AutoGetTemplate();
                    //if ((set2 != null) && (set2.Tables[0].Rows.Count > 0))
                    //{
                    //    this.AutoSetTemplate(set2);
                    //}
                    //DataSet set3 = new DataSet();
                    //set3 = this.AutoGetTSMS();
                    //if ((set3 != null) && (set3.Tables[0].Rows.Count > 0))
                    //{
                    //    this.AutoSetSMS(set3);
                    //}
                    SendGouYaoTip();
                    //
                    Transfer();

                    //处理优惠券
                    IBussiness buss = new CouponBussiness();
                    buss.Process();
                    //RemoveOutdateOrder();
                    base.Response.Write("发送成功!");
                }
                catch (Exception exception)
                {
                    base.Response.Write(exception.Message);
                }
            //}
            //else
            //{
            //    base.Response.Write("不在设定的发送时间内!");
            //}
        }

        private void SendGouYaoTip()
        {
            DataSet ds = AutoGetTemplate();
            AutoSetTemplate(ds);
        }

        private void RemoveOutdateOrder()
        {
            string strdt = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd hh:mm:ss");
            IList<Model.orders> morders = new BLL.orders().GetModelList(" status < 2 and add_time<'" + strdt + "' ");
            BLL.orders border = new BLL.orders();
            
            foreach (Model.orders item in morders)
            {
                border.Delete(item.id);
            }
        }
        private void SendSMSMessage(string phone, string contenttxt)
        {
            string htmlFromUrl = this.GetHtmlFromUrl(phone, contenttxt);
        }

        private void SendWxMessage(int id)
        {
            BLL.orders border = new BLL.orders();
            DataSet set = border.SelectOrderInfo(id);
            string openid = set.Tables[0].Rows[0]["openid"].ToString();
            decimal amount = decimal.Parse(set.Tables[0].Rows[0]["amount"].ToString());
            int shopid = int.Parse(set.Tables[0].Rows[0]["shopid"].ToString());
            int wid = int.Parse(set.Tables[0].Rows[0]["wid"].ToString());
            decimal sumamount = decimal.Parse(set.Tables[0].Rows[0]["sumamount"].ToString());
            string url = string.Concat(new object[] { MyCommFun.getWebSite(), "/wxoauth.aspx?wid=", wid, "&p=6" });
            string phone = set.Tables[0].Rows[0]["mobile"].ToString();
            string nick_name = set.Tables[0].Rows[0]["nick_name"].ToString();
            string pnick_name = set.Tables[0].Rows[0]["pnick_name"].ToString();
            string msg = string.Empty;
            string pwxopenid = set.Tables[0].Rows[0]["pwxopenid"].ToString();
            string ppwxopenid = set.Tables[0].Rows[0]["ppwxopenid"].ToString();
            decimal pamount = decimal.Parse(set.Tables[0].Rows[0]["pamount"].ToString());
            decimal psumamount = decimal.Parse(set.Tables[0].Rows[0]["psumamount"].ToString());
            string pmobile = set.Tables[0].Rows[0]["pmobile"].ToString();
            string ppmobile = set.Tables[0].Rows[0]["ppmobile"].ToString();
            string ppnick_name = set.Tables[0].Rows[0]["ppnick_name"].ToString();
            decimal ppamount = decimal.Parse(set.Tables[0].Rows[0]["ppamount"].ToString());
            decimal ppsumamount = decimal.Parse(set.Tables[0].Rows[0]["ppsumamount"].ToString());
            if ((openid != null) && !openid.Equals(""))
            {
                if (amount > 0M)
                {
                    this.sm.SendMessageShouHuo("1", openid, wid, amount, sumamount, "", "", url);
                }
                else if (amount < 0M)
                {
                    this.sm.SendMessageShouHuo("2", openid, wid, amount, sumamount, "", "", url);
                }
            }
            else if (((phone != null) && !phone.Equals("")) && border.isAllowSend(shopid))
            {
                msg = string.Concat(new object[] { "尊敬的", nick_name, "您本次购物获得积分：", amount, "分" });
                this.SendSMSMessage(id, shopid, phone, nick_name,wid, msg);
            }
            if ((pwxopenid != null) && !pwxopenid.Equals(""))
            {
                if (pamount > 0M)
                {
                    this.sm.SendMessageShouHuo("1", pwxopenid, wid, pamount, psumamount, nick_name, "", url);
                }
                else if (pamount < 0M)
                {
                    this.sm.SendMessageShouHuo("2", pwxopenid, wid, pamount, psumamount, nick_name, "", url);
                }
            }
            else if (((pmobile != null) && !pmobile.Equals("")) && new BLL.orders().isAllowSend(shopid))
            {
                msg = string.Concat(new object[] { "尊敬的", pnick_name, "您邀请的", nick_name, "完成交易您获得积分：", pamount, "分" });
                this.SendSMSMessage(id, shopid, pmobile, pnick_name,shopid, msg);
            }
            if ((ppwxopenid != null) && !ppwxopenid.Equals(""))
            {
                if (ppamount > 0M)
                {
                    this.sm.SendMessageShouHuo("1", ppwxopenid, wid, ppamount, ppsumamount, pnick_name, nick_name, url);
                }
                else if (ppamount < 0M)
                {
                    this.sm.SendMessageShouHuo("2", ppwxopenid, wid, ppamount, ppsumamount, pnick_name, nick_name, url);
                }
            }
            else if (((ppmobile != null) && !ppmobile.Equals("")) && new BLL.orders().isAllowSend(shopid))
            {
                msg = string.Concat(new object[] { "您邀请的", pnick_name, "的下级", nick_name, "完成交易您获得积分：", ppamount, "分" });
                this.SendSMSMessage(id, shopid, ppmobile, ppnick_name,shopid, msg);
            }
        }

        private void SendSMSMessage(int id, int shopid, string phone, string nick_name,int wid, string contenttxt)
        {
            string htmlFromUrl = this.GetHtmlFromUrl(phone, contenttxt);
            if (!(string.IsNullOrEmpty(htmlFromUrl) || htmlFromUrl.Equals("")))
            {
                int num = new BLL.orders().AddInfo(nick_name, phone, id, contenttxt, "1", wid, shopid);
            }
        }

        public SortedDictionary<string, object> FromXml(string xml)
        {
            SortedDictionary<string, object> m_values = new SortedDictionary<string, object>();
            if (string.IsNullOrEmpty(xml))
            {
                return null;
            }

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(xml);
            XmlNode xmlNode = xmlDoc.FirstChild;//获取到根节点<xml>
            XmlNodeList nodes = xmlNode.ChildNodes;
            foreach (XmlNode xn in nodes)
            {
                XmlElement xe = (XmlElement)xn;
                m_values[xe.Name] = xe.InnerText;//获取xml的键值对到WxPayData内部的数据中
            }
            return m_values;
        }
    }
}